console.log('Background script loaded (ollama)');

let apiUrl = 'http://192.168.1.24:11434'
let model = 'qwen2.5:7b'

// 读取prompt.txt中的分类提示词
let prompts = '';
let promptsLoaded = false;

fetch(chrome.runtime.getURL('prompt.txt'))
  .then(response => response.text())
  .then(text => {
    prompts = text;
    promptsLoaded = true;
    // console.log('提示词加载完成');
  })
  .catch(error => {
    console.error('读取提示词失败:', error);
    prompts = '默认提示词: 请总结这个工单对话';
    promptsLoaded = true;
  });

// 调用Ollama API
async function callOllama(prompt, model) {    
    try {
        console.log('正在生成响应...');
        const startTime = Date.now(); // 记录开始时间
        
        const response = await fetch(`${apiUrl}/api/generate`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                model: model,
                prompt: prompt,
                stream: false
            })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP错误: ${response.status}`);
        }
        
        const data = await response.json();
        const endTime = Date.now(); // 记录结束时间
        const duration = endTime - startTime; // 计算用时
        
        console.log(`API调用完成，用时: ${duration}ms`);
        console.log('就绪');
        
        return {
            response: data.response,
            duration: duration
        };
    } catch (error) {
        console.error('调用Ollama API时出错:', error);
        console.log(`错误: ${error.message}`);
        return {
            response: `抱歉，发生了错误: ${error.message}`,
            duration: 0
        };
    }
}

// 发送消息处理
async function sendContent(conversation) {
    if (!conversation) return;
    
    const messages = [
        {
          role: "system",
          content: prompts
        },
        {
          role: "user",
          content: `请根据以下对话内容进行分类和总结：\n\n${
            conversation.map(msg => `${msg.role}: ${msg.content}`).join('\n')
          }`
        }
      ]
      
    const startTime = Date.now(); // 记录总开始时间
    const result = await callOllama(JSON.stringify(messages), model);
    const endTime = Date.now(); // 记录总结束时间
    const totalDuration = endTime - startTime; // 计算总用时
    
    return {
        summary: result.response,
        apiDuration: result.duration,
        totalDuration: totalDuration
    };
}

// 监听content.js的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'summarize') {
    if (!promptsLoaded) {
      sendResponse({error: '提示词正在加载，请稍后再试'});
      return true;
    }

    const conversation = request.data;
    console.log('收到对话内容:', conversation);

    // 使用async函数处理异步操作
    (async () => {
      try {
        const processStartTime = Date.now(); // 记录整个处理开始时间
        const result = await sendContent(conversation);
        const processEndTime = Date.now(); // 记录整个处理结束时间
        
        console.log('生成的摘要:', result.summary);
        console.log(`完整处理流程用时: ${processEndTime - processStartTime}ms`);
        
        // 提取JSON部分（如果返回的是带```json标记的文本）
        let jsonStr = result.summary;
        if (result.summary.includes('```json')) {
          const jsonMatch = result.summary.match(/```json\s*\n?([\s\S]*?)```/);
          jsonStr = jsonMatch ? jsonMatch[1].trim() : null;
        }
        
        const summary_obj = JSON.parse(jsonStr);

        // 发送回content.js，同时包含用时信息
        chrome.tabs.sendMessage(sender.tab.id, {
          action: 'fill',
          category_id: summary_obj.category_id,
          category_name: summary_obj.category_name,
          description: summary_obj.description,
          timing: {
            apiDuration: result.apiDuration,
            totalDuration: result.totalDuration,
            processDuration: processEndTime - processStartTime
          }
        });
      } catch (error) {
        console.error('处理摘要时出错:', error);
        // 发送错误信息回content.js
        chrome.tabs.sendMessage(sender.tab.id, {
          action: 'error',
          error: error.message,
          result: jsonStr,
        });
      }
    })();
    
    // 返回true表示会异步发送响应
    return true;
  }
});